<?php
namespace App\Services;
use App\Librarys\Wechatcrypts\Wxbizmsgcrypt;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Client;
use App\Models\Workcorps;
use Config,Log,Exception;

class WorkcustomService
{
    // 获取企业三方应用凭证
    public static function getSuiteToken($suite_id)
    {
        try {            
            $suite_id = empty($suite_id) ? "ww0bb7c683e57eb173" : $suite_id;
            $config = Config::get("weixin.work.".$suite_id);
            $suite_access_token = Redis::get("work_suite_access_token_".$suite_id);
            if (empty($suite_access_token)) {
                $suite_ticket = Redis::get("open_work_suite_ticket_".$suite_id);
                $client = new Client();
                $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token", ["json" => ["suite_id"=>$config["suite_id"],"suite_secret"=>$config["suite_secret"],"suite_ticket"=>$suite_ticket]],["timeout"=>3]);
                $body = $response->getBody()->getContents();
                $token = json_decode($body,true);
                $suite_access_token = $token["suite_access_token"];
                Redis::setex("work_suite_access_token_".$suite_id,7100,$suite_access_token);
            }
            return $suite_access_token;
        } catch (Exception $e) {
            return "";
        }
    }

    // 获取企业access_token
    public static function getCropAccessTokenObject($corp_id)
    {
        $access_token = Redis::get("crop_access_token_".$corp_id);
        if (empty($access_token)) {
            $client = new Client();
            $kfcorp = Workcorps::getKfCorpsPermanentCode($corp_id);
            if (empty($kfcorp)) return "";
            $suite_access_token = self::getSuiteToken($kfcorp->suite_id);
            $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"permanent_code"=>$kfcorp->permanent_code]],["timeout"=>3]);
            $body = $response->getBody()->getContents();
            $token = json_decode($body,true);
            if (!isset($token["access_token"])) return ["status"=>"error","errcode"=>$token["errcode"],"access_token"=>""];
            $access_token = $token["access_token"];
            Redis::setex("crop_access_token_".$corp_id,7100,$access_token);
        }
        return ["status"=>"success","errcode"=>0,"access_token"=>$access_token];
    }

    // 获取企业access_token
    public static function getCropAccessToken($corp_id)
    {
        $access_token = Redis::get("crop_access_token_".$corp_id);
        if (empty($access_token)) {
            $client = new Client();
            $kfcorp = Workcorps::getKfCorpsPermanentCode($corp_id);
            if (empty($kfcorp)) return "";
            $suite_access_token = self::getSuiteToken($kfcorp->suite_id);
            $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"permanent_code"=>$kfcorp->permanent_code]],["timeout"=>3]);
            $body = $response->getBody()->getContents();
            $token = json_decode($body,true);
            if (!isset($token["access_token"])) return "";
            $access_token = $token["access_token"];
            Redis::setex("crop_access_token_".$corp_id,7100,$access_token);
        }
        return $access_token;
    }

    // 强制获取企业access_token
    public static function getCropAccessTokenFroch($corp_id)
    {
        $client = new Client();
        $kfcorp = Workcorps::getKfCorpsPermanentCode($corp_id);
        $suite_access_token = self::getSuiteToken($kfcorp->suite_id);
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"permanent_code"=>$kfcorp->permanent_code]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        $token = json_decode($body,true);
        if (!isset($token["access_token"])) return "";
        $access_token = $token["access_token"];
        Redis::setex("crop_access_token_".$corp_id,7100,$access_token);
        return $access_token;
    }

    // 获取预授权码
    public static function getPreAuthCode($suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("GET", "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=".$suite_access_token,["timeout"=>3]);
        $body = $response->getBody()->getContents();
        $result = json_decode($body,true);
        return $result;
    }

    // 获取企业授权信息
    public static function getAuthInfo($auth_corpid,$permanent_code,$suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$auth_corpid,"permanent_code"=>$permanent_code]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 获取带参授权链接
    public static function getCustomizedAuthUrl($state,$templateid_list,$suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_customized_auth_url?provider_access_token=".$suite_access_token, ["json" => ["state"=>$state,"templateid_list"=>$templateid_list]]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 获取企业永久授权码
    public static function getPermanentCode($auth_code,$suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=".$suite_access_token, ["json" => ["auth_code"=>$auth_code]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 通讯录单个搜索
    public static function contactSearch($corp_id,$query_word)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/contact/search?provider_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"query_word"=>$query_word,"full_match_field"=>1]]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 三方获取客户基本信息
    public static function externalContactGet($corp_id,$external_userid)
    {
        $access_token = self::getCropAccessToken($corp_id);
        if (empty($access_token)) return ["errcode"=>"10001","msg"=>"获取AccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=".$access_token."&external_userid=".$external_userid."&cursor=");
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 手机号获取userid
    public static function getUserId($corp_id,$mobile)
    {
        $access_token = self::getCropAccessToken($corp_id);
        if (empty($access_token)) return ["errcode"=>"10001","msg"=>"获取AccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=".$access_token, ["json" => ["mobile"=>$mobile]]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 邮箱获取userid
    public static function getUseridByEmail($corp_id,$email)
    {
        $access_token = self::getCropAccessToken($corp_id);
        if (empty($access_token)) return ["errcode"=>"10001","msg"=>"获取AccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("POST","https://qyapi.weixin.qq.com/cgi-bin/user/get_userid_by_email?access_token=".$access_token, ["json" => ["email"=>$email,"email_type"=>1]]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 获取访问用户身份
    public static function getUserInfo3rd($suite_id,$code)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        if (empty($suite_access_token)) return ["errcode"=>"10001","errmsg"=>"获取SuiteAccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("GET", "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?suite_access_token=".$suite_access_token."&code=".$code);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 获取访问用户敏感信息,只能获取头像
    public static function getUserDetail3rd($user_ticket)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        if (empty($suite_access_token)) return ["errcode"=>"10001","errmsg"=>"获取SuiteAccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?suite_access_token=".$suite_access_token, ["json" => ["user_ticket"=>$user_ticket]]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // corpid的转换
    public static function corpidToOpencorpid($suite_id,$corpid)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        if (empty($suite_access_token)) return ["errcode"=>"10001","errmsg"=>"获取SuiteAccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/corpid_to_opencorpid?provider_access_token=".$provider_access_token, ["json" => ["corpid"=>$corpid]]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

}
